//
//  PopoverPresentationController.swift
//  PopViewMenu
//
//  Created by Rookie_YX on 16/5/27.
//  Copyright © 2016年 YX_Rookic. All rights reserved.
//

import UIKit

class PopoverPresentationController: UIPresentationController {
    // 定义属性保存菜单大小
    var presentFrame = CGRectZero
    
    /**
     初始化方法, 用于创建负责转场动画的对象
     
     - parameter presentedViewController:  被展现的控制器
     - parameter presentingViewController: 发起控制器  注:在xcode6打印为nil,xocde7打印为野指针
     
     - returns: 负责转场动画的对象
     */
    
    override init(presentedViewController: UIViewController, presentingViewController: UIViewController) {
        super.init(presentedViewController: presentedViewController, presentingViewController: presentingViewController)
        
    }
    
    
    /**
     即将布局转场子图调用
     */
    override func containerViewWillLayoutSubviews() {
        // 修改弹出视图的大小
        if presentFrame == CGRectZero {
            let PVwidth:CGFloat = 200
            let PVx:CGFloat = (UIScreen.mainScreen().bounds.width - PVwidth) / 2
            let PVy:CGFloat = 59
            let PVheight:CGFloat = 200
            presentedView()?.frame = CGRect(x: PVx, y: PVy, width:PVwidth, height:PVheight)
        }
        else{
            presentedView()?.frame = presentFrame
        }
        // 在容器视图上添加一个蒙版
        containerView?.insertSubview(coverView, atIndex: 0)
    }
    
    // MARK:-
    // MARK:-  懒加载
    private lazy var coverView:UIView = {
        // 创建view
        let view = UIView()
        view.frame = UIScreen.mainScreen().bounds
        view.backgroundColor = UIColor(white: 0.0, alpha: 0.2)
        
        // 添加监听
        let tap = UITapGestureRecognizer(target: self, action: #selector(PopoverPresentationController.closeCoverView))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    func closeCoverView(){
        presentedViewController.dismissViewControllerAnimated(true, completion: nil)
    }

}
